import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dms_documentlocation_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/dms_documentlocation.dart';
import 'package:flutter_admin/pages/odoo/dms_documentlocation/dms_documentlocation_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';

class DmsDocumentlocationList extends StatefulWidget {
  DmsDocumentlocationList({Key? key}) : super(key: key);

  @override
  _DmsDocumentlocationListState createState() =>
      _DmsDocumentlocationListState();
}

class _DmsDocumentlocationListState extends State<DmsDocumentlocationList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  DmsDocumentlocation dmsDocumentlocation = DmsDocumentlocation();
  List<DmsDocumentlocation> selectedList = [];
  //所属区域
  List<SelectOptionVO> areaList = [];
  @override
  void initState() {
    _loadSelectVO();
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    //所属区域
    areaList = await DynamicDataApi.getModelSelect(
        active: false, model: "dms.documentarea", name: "areaname");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 160,
            label: '档案区域',
            dataList: areaList,
            value: dmsDocumentlocation.areaId,
            onSaved: (v) => {dmsDocumentlocation.areaId = v},
          ),
          CryInput(
            width: 140,
            label: '位置编码',
            value: dmsDocumentlocation.locationcode,
            onSaved: (v) {
              dmsDocumentlocation.locationcode = v;
            },
          ),
          CryInput(
            width: 140,
            label: '位置名称',
            value: dmsDocumentlocation.locationname,
            onSaved: (v) {
              dmsDocumentlocation.locationname = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('档案区域')),
        DataColumn(label: Text('位置编码')),
        DataColumn(label: Text('位置名称')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建时间')),
      ],
      getCells: (m) {
        DmsDocumentlocation dmsDocumentlocation =
            DmsDocumentlocation.fromMap(m);
        return [
          DataCell(Text(dmsDocumentlocation.areaName ?? '--')),
          DataCell(Text(dmsDocumentlocation.locationcode ?? '--')),
          DataCell(Text(dmsDocumentlocation.locationname ?? '--')),
          DataCell(Text(dmsDocumentlocation.remark ?? '--')),
          DataCell(Text(dmsDocumentlocation.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(dmsDocumentlocation.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.print(
          context,
          selectedList.length != 0 ? () => _print(selectedList) : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 0),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              ),
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    dmsDocumentlocation = DmsDocumentlocation();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await DmsDocumentlocationOdooApi.page(
        data: {"page": page, "domainList": dmsDocumentlocation.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: DmsDocumentlocationDialog(),
      ),
    ).then((v) {
      if (v != null) {
        dmsDocumentlocation = v;
        _query();
      }
    });
  }

  _print(List<DmsDocumentlocation> dmsDocumentlocationList) async {
    String data = "";
    for (var i = 0; i < dmsDocumentlocationList.length; i++) {
      if (i != dmsDocumentlocationList.length - 1) {
        data += dmsDocumentlocationList[i].locationcode!;
        data += ";";
        continue;
      }
      data += dmsDocumentlocationList[i].locationcode!;
    }
    ResponseBodyApi res = await DynamicDataApi.devicePrint(data: data);
    if (res.success!) {
      CryUtils.message("打印成功");
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<DmsDocumentlocation>((e) => DmsDocumentlocation.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.print) {
          _print(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.print,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.print_rounded),
            enabled: selectedList.length != 0,
            title: Text('打印'),
          ),
        ),
      ],
    );
  }
}
